<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 顶部数据 -->
                <div style="margin-top:10px;display: flex;">
                    <el-tag type="success">收入:{{ totalGath }}元</el-tag>
                    <el-divider direction="vertical"></el-divider>
                    <el-tag type="danger">支出:{{ totalPay }}元</el-tag>
                    <el-divider direction="vertical"></el-divider>
                    <el-tag type="warning">余额:{{ getBalance }}元</el-tag>
                    <el-select @change="findBankCombo_change" style="margin-left: 20px;" v-model="findBankCombo_data"
                        clearable placeholder="银行名称">
                        <el-option v-for="item in findBankCombo_list" :key="item.id" :label="item.bankName"
                            :value="item.id" />
                    </el-select>
                    <div style="margin-left:15px">
                        <el-button v-if="!findBankCombo_data" @click="importfeeBtl_btn" type="primary"
                            icon="Upload">银行账导入</el-button>
                        <!-- :headers="{ 'token': GET_TOKEN(), 'Content-Type': 'multipart/form-data' }" -->
                        <el-upload v-else
                            :data="{ btlFile: myBank.btlFile, myBankName: myBank.myBankName, myBankNum: myBank.myBankNum }"
                            :headers="{ 'token': GET_TOKEN(), }" class="upload-excel" :action="importfeeBtl"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                            <el-button type="primary" icon="Upload">银行账导入</el-button>
                        </el-upload>
                    </div>
                    <el-button style="margin-left:15px" @click="btlModelDown_btn" type="primary"
                        icon="Download">模版下载</el-button>
                </div>
                <!-- 搜索 -->
                <div style="margin-top:10px;">
                    <el-input style="width: 150px;" v-model="find_data.transName" placeholder="对方户名" clearable />
                    <el-input style="width: 150px;margin-left:10px" v-model="find_data.cusName" placeholder="客户名称"
                        clearable />
                    <el-select style="width: 100px;margin-left:10px" v-model="find_data.timeType" placeholder="Select">
                        <el-option v-for="item in timeType_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-date-picker :default-time="defaultTime" style="margin-left: 10px;width: 340px;height:30px"
                        v-model="timeTypeTime" @change="timeTypeTime_btn" type="datetimerange" start-placeholder="开始时间"
                        end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                    <el-input style="width: 100px;margin-left:10px" v-model="find_data.tradeMoney" placeholder="交易金额"
                        clearable />
                    <el-select clearable style="width: 100px;margin-left:10px" v-model="find_data.isCheck"
                        placeholder="报销状态">
                        <el-option v-for="item in isCheck_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>

                    <el-select multiple collapse-tags collapse-tags-tooltip @change="moneyTypeIds_chang" clearable
                        style="width: 150px;margin-left:10px" v-model="find_data.moneyTypeIds" placeholder="请选择金额类型">
                        <el-option v-for="item in findMtypeCombo_list" :key="item.id" :label="item.typeName"
                            :value="item.id" />
                    </el-select>

                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-input style="width: 150px;margin-left:10px" v-model="find_data.operMark" placeholder="操作编号"
                        clearable />
                    <el-input style="width: 150px;margin-left:10px" v-model="find_data.remark" placeholder="摘要"
                        clearable />
                    <!-- <el-select clearable style="width: 150px;margin-left:10px" v-model="find_data.settleUname"
                    placeholder="结算人选择">
                    <el-option v-for="item in upManageOptions" :key="item.ftUserId" :label="item.realName"
                        :value="item.ftUserId" />
                </el-select> -->

                    <el-select clearable style="width: 100px;margin-left:10px" v-model="find_data.tradeStatus"
                        placeholder="收支情况">
                        <el-option v-for="item in tradeStatus_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <el-button style="margin-left: 10px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                    <!-- <el-button type="primary" icon="Calendar">月结算</el-button> -->
                    <el-button @click="ex_getWalletListForBack_btn" type="primary" icon="Share">导出</el-button>
                    <el-button @click="transfer_btn" type="primary" icon="Tickets">转账</el-button>
                    <el-button @click="confirmTransEach_btn" type="primary" icon="Memo">确认互转</el-button>
                    <el-button @click="downBtlRecharge_btn" type="primary" icon="Collection">银行账充值下账</el-button>
                </div>
            </template>
            <div>
                <el-table border @header-dragend='headerdragend' @selection-change="selection_change_btn" height="61vh"
                    ref="multipleTableRef" :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'isCheck'" #="{ row, column, $index }">
                                {{ row.isCheck == 'REFUSED' ? '已拒绝' : row.isCheck == 'NO_CHECK' ? '未审核' :
                                    row.isCheck
                                        ==
                                        'CHECKED' ? '已审核' : row.isCheck == 'CANCELLATION' ? '已报销' : row.isCheck == 'SETTLED' ?
                                            '已结算' : '' }} </template>
                            <template v-if="item.field == 'cusName'" #="{ row, column, $index }">
                                {{ cusName_api(row.cusName) }}
                            </template>
                            <template v-if="item.field == 'operNote'" #="{ row, column, $index }">

                                <el-tooltip :popper-class="'route-tips'" placement="left">
                                    <template #content>{{ row.operNote }}</template>
                                    <span style="  width: 100px; white-space: nowrap; text-overflow: ellipsis; ">{{
                                        row.operNote }}</span>
                                </el-tooltip>

                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" ref="formRef" label-width="130px" label-suffix="：">
                <el-form-item label="我的银行" prop="myBankName" :rules="[
                    { required: true, message: '请选择银行名称', trigger: 'blur' },
                ]">
                    <el-select :disabled="form_off" @change="myBankName_change" style="width: 400px;"
                        v-model="add_data.myBankName" clearable placeholder="银行名称">
                        <el-option v-for="item in findBankCombo_list" :key="item.id" :label="item.bankName"
                            :value="item.bankName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="银行卡号" prop="myBankName" :rules="[
                    { required: true, message: '请选择银行名称', trigger: 'blur' },
                ]">
                    <el-input disabled style="width: 400px;" v-model="add_data.myBankNum" placeholder="请选择银行名称自动查询" />
                </el-form-item>

                <el-form-item label="客户名称" :rules="[
                    { required: false, message: '请输入客户名称', trigger: 'blur' },
                ]">
                    <el-select style="width: 400px;" filterable remote clearable @change="queryCusPageList_select_Btn"
                        :filter-method="queryCusPageList" v-model="add_data.cusName" placeholder="请选择客户名称">
                        <el-option v-for="(item, index) in cusOptions" :key="index" :label="item.cusCompanyName"
                            :value="item.cusRealName + ',' + item.cusPhone">
                            <span style="float: left">{{ item.cusCompanyName }}</span>
                            <span style="
                            float: right;
                            color: var(--el-text-color-secondary);
                            font-size: 13px;
                          ">{{ item.cusRealName + '（' + item.cusPhone + '）' }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="对方户名" prop="transName" :rules="[
                    { required: false, message: '请输入对方户名', trigger: 'blur' },
                ]">
                    <el-input style="width: 400px;" v-model="add_data.transName" placeholder="请输入对方户名" />
                </el-form-item>
                <el-form-item label="对方账号" :rules="[
                    { required: false, message: '请输入对方账号', trigger: 'blur' },
                ]">
                    <el-input :disabled="form_off" style="width: 400px;" v-model="add_data.transNum"
                        placeholder="请输入客户名称" />
                </el-form-item>
                <el-form-item label="收支状态" prop="tradeStatus" :rules="[
                    { required: true, message: '请选择收支状态', trigger: 'blur' },
                ]">
                    <el-select @change='change_tradeStatus' :disabled="form_off" clearable style="width: 400px;"
                        v-model="add_data.tradeStatus" placeholder="请选择收支状态">
                        <el-option v-for="item in tradeStatus_list" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="zhichu" label="金额类型" prop="moneyTypeId" :rules="[
                    { required: false, message: '请选择金额类型', trigger: 'blur' },
                ]">
                    <el-select style="width: 400px;" v-model="add_data.moneyTypeId" placeholder="请选择金额类型" clearable>
                        <el-option v-for="item in findMtypeCombo_list" :key="item.id" :label="item.typeName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item :disabled="form_off" label="交易时间" prop="tradeTime" :rules="[
                    { required: true, message: '请选择交易时间', trigger: 'blur' },
                ]">
                    <el-date-picker style="width: 400px;" v-model="add_data.tradeTime" type="datetime"
                        placeholder="请选择交易时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="交易金额" prop="tradeMoney" :rules="[
                    { required: true, message: '请输入交易金额', trigger: 'blur' },
                ]">
                    <el-input @change='change_tradeMoney' :disabled="form_off" style="width: 400px;" type="number"
                        v-model="add_data.tradeMoney" placeholder="请输入交易金额" />
                </el-form-item>
                <el-form-item label="余额" prop="balance" :rules="[
                    { required: true, message: '请选择银行名称', trigger: 'blur' },
                ]">
                    <el-input disabled style="width: 400px;" v-model="add_data.balance" placeholder="请选择银行名称自动查询" />
                </el-form-item>
                <el-form-item label="摘要" :rules="[
                    { required: false, message: '请输入摘要', trigger: 'blur' },
                ]">
                    <el-input clearable show-word-limit maxlength="500" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" style="width: 400px;" v-model="add_data.remark" placeholder="请输入摘要" />
                </el-form-item>

            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 张转 -->
        <el-dialog style="margin-top:5vh" v-model="transfer_off" title="银行账转账" width="40%"
            :close-on-click-modal='false'>
            <el-form :model="transfer_data" ref="formRef" label-width="130px" label-suffix="：">
                <el-form-item label="转出银行名称" prop="myBankName" :rules="[
                    { required: false, message: '请选择转出银行名称', trigger: 'blur' },
                ]">
                    <el-select @change="transfer_myBankName_change" style="width: 400px;"
                        v-model="transfer_data.myBankName" clearable placeholder="转出银行名称">
                        <el-option v-for="item in findBankCombo_list" :key="item.id" :label="item.bankName"
                            :value="item.bankName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="转出银行卡号" prop="myBankName" :rules="[
                    { required: false, message: '请选择转出银行卡号', trigger: 'blur' },
                ]">
                    <el-input disabled style="width: 400px;" v-model="transfer_data.myBankNum"
                        placeholder="请选择转出银行卡号" />
                </el-form-item>


                <el-form-item label="转入银行名称" prop="transName" :rules="[
                    { required: false, message: '请输入转入银行名称', trigger: 'blur' },
                ]">
                    <el-select @change="transfer_myBankName_change2" style="width: 400px;"
                        v-model="transfer_data.transName" clearable placeholder="请输入转入银行名称">
                        <el-option v-for="item in findBankCombo_list" :key="item.id" :label="item.bankName"
                            :value="item.bankName" />
                    </el-select>
                    <!-- <el-input style="width: 400px;" v-model="transfer_data.transName" placeholder="" /> -->
                </el-form-item>
                <el-form-item label="转入银行卡号" :rules="[
                    { required: false, message: '请输入转入银行卡号', trigger: 'blur' },
                ]">
                    <el-input disabled style="width: 400px;" v-model="transfer_data.transNum" placeholder="请输入转入银行卡号" />
                </el-form-item>
                <el-form-item label="转账金额" prop="tradeMoney" :rules="[
                    { required: false, message: '请输入转账金额', trigger: 'blur' },
                ]">
                    <el-input style="width: 400px;" type="number" v-model="transfer_data.tradeMoney"
                        placeholder="请输入转账金额" />
                </el-form-item>
                <el-form-item label="转账时间" prop="tradeTime" :rules="[
                    { required: false, message: '请选择转账时间', trigger: 'blur' },
                ]">
                    <el-date-picker style="width: 400px;" v-model="transfer_data.tradeTime" type="datetime"
                        placeholder="请选择转账时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>


                <el-form-item label="摘要" :rules="[
                    { required: false, message: '请输入摘要', trigger: 'blur' },
                ]">
                    <el-input clearable show-word-limit maxlength="500" :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea" style="width: 400px;" v-model="transfer_data.remark" placeholder="请输入摘要" />
                </el-form-item>

            </el-form>


            <el-button @click="transfer_ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 互转 -->
        <el-dialog style="margin-top:5vh" v-model="confirmTransEach_off" title="银行账确认互转" width="50%"
            :close-on-click-modal='false'>
            <el-form :inline="true">

                <el-form-item>
                    <el-tag v-if="confirmTransEach_on == 1" type="success">转 入</el-tag>
                    <el-tag v-else type="danger">转 出</el-tag>

                </el-form-item>
                <el-form-item>
                    客户名称:{{ cusName_api(table_list[0].cusName) }}
                </el-form-item>

                <el-form-item>
                    银行名称:{{ table_list[0].myBankName }}

                </el-form-item>
                <el-form-item>
                    银行账号:{{ table_list[0].myBankNum }}

                </el-form-item>
                <el-form-item>
                    交易时间:{{ table_list[0].tradeTime }}

                </el-form-item>

            </el-form>
            <el-form :inline="true">
                <el-form-item>
                    <el-tag v-if="confirmTransEach_on == 2" type="success">转 入</el-tag>
                    <el-tag v-else type="danger">转 出</el-tag>
                </el-form-item>
                <el-form-item>
                    客户名称:{{ cusName_api(table_list[1].cusName) }}
                </el-form-item>

                <el-form-item>
                    银行名称:{{ table_list[1].myBankName }}

                </el-form-item>
                <el-form-item>
                    银行账号:{{ table_list[1].myBankNum }}

                </el-form-item>
                <el-form-item>
                    交易时间:{{ table_list[1].tradeTime }}

                </el-form-item>

            </el-form>

            <div style="display: flex;margin-left:35vw">
                <el-button @click="qiehuan" type="warning">转入转出切换</el-button>
                <el-button @click="confirmTransEach_ok_btn" type="primary">确认提交</el-button>
            </div>
        </el-dialog>
        <!-- 银行账充值下账 -->
        <el-dialog style="margin-top:30vh" v-model="downBtlRecharge_off" title="银行账充值下账" width="30%"
            :close-on-click-modal='false'>
            <el-form :inline="true">
                <el-form-item>
                    <el-select style="width: 400px;" filterable remote clearable :filter-method="queryCusPageList"
                        v-model="downBtlRecharge_data.userId" placeholder="请选择客户名称">
                        <el-option v-for="(item, index) in cusOptions" :key="index" :label="item.cusCompanyName"
                            :value="item.userId">
                            <span style="float: left">{{ item.cusCompanyName }}</span>
                            <span style="
                            float: right;
                            color: var(--el-text-color-secondary);
                            font-size: 13px;
                          ">{{ item.cusRealName + '（' + item.cusPhone + '）' }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>


            </el-form>


            <div style="display: flex;margin-left:20vw">
                <el-button @click="downBtlRecharge_ok_btn" type="primary">确认提交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import * as XLSX from 'xlsx';
import Sortable from 'sortablejs';
import { GET_TOKEN } from '@/utils/token.js'
import { ref, reactive, onMounted, computed } from 'vue'
import {
    adupPrivateSet, getPrivateSetList, findBankTradeList, findBankCombo, btlModelDown, findMtypeCombo,
    findStaffCombo, findBalanceByBankInfo, addBtl, delBtl, modifyBtl, expBtlBankEx, findComboCusList, transfer,
    confirmTransEach, downBtlRecharge

} from '@/api/financial_center.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { importCusCheckInData, downFiles, importfeeBtl } from '@/utils/common.js'
import CircularJSON from 'circular-json'
onMounted(async () => {
    let bank_statement = JSON.parse(localStorage.getItem('bank_statement'))
    // if (bank_statement) {
    //     find_data.cusName = bank_statement.cusName
    // }
    getPrivateSetList({
        find: '银行流水',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);
        }
    })


    findBankCombo({}).then(res => {
        findBankCombo_list.value = res.data
    })
    findMtypeCombo({}).then(res => {
        findMtypeCombo_list.value = res.data
    })
    findStaffCombo({}).then(res => {
        upManageOptions.value = res.data
    })
    findComboCusList({
        find: '',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.code == 1) {
            cusOptions.value = res.data;
            cusOptions2.value = res.data;

            // 追加已选中的数据
            // if (cusObjArr.value.length > 0) cusOptions.value = cusObjArr.value.concat(cusOptions.value);
        }
    })

    await list_api()

})
const cusName_api = (e) => {
    let data = ''
    if (e) {
        let arr = e.split('/@')
        if (arr) {
            let arr_data = []
            for (let i = 0; i < arr.length; i++) {
                arr_data.push(arr[i].split(',')[0])
            }
            data = arr_data.join(',')


        } else {
            data = e.split(',')[0]

        }
    }

    return data
}
const cusIds = ref([])
const cusObjArr = ref([])
const cusOptions = ref([])
const cusOptions2 = ref([])
const queryCusPageList_select_Btn = (e) => {
    console.log(e)
}
const queryCusPageList = (value) => {
    // 自定义筛选逻辑
    if (value) {
        let results = cusOptions2.value.filter(item => {
            for (let key in item) {
                if (typeof item[key] === 'string' && item[key].includes(value)) {
                    return true;
                }
            }
            return false;
        })
        if (results.length > 0) {
            cusOptions.value = results
        } else {
            cusOptions.value = []
        }
    } else {
        cusOptions.value = cusOptions2.value
    }
}
// const queryCusPageList = (query) => {
//     if (!query) return (cusOptions.value = []);
//     findComboCusList({
//         find: query,
//         page: {
//             pageNum: 1,
//             pageSize: 20,
//         },
//     }).then(res => {
//         if (res.code == 1) {
//             cusOptions.value = res.data;

//             // 追加已选中的数据
//             // if (cusObjArr.value.length > 0) cusOptions.value = cusObjArr.value.concat(cusOptions.value);
//         }
//     })
// }
const selCusName = (obj) => {
    // console.log(obj)

    // let index = cusObjArr.value.findIndex(it => it.id == obj.id);
    // let is = cusIds.value.findIndex(it => it == obj.id);
    // if (is != -1) {// 存在，表示添加
    //     if (index == -1) cusObjArr.value.push(obj);
    // } else {// 不存在，表示删除
    //     if (index != -1) cusObjArr.value.splice(index, 1);
    // }
}
//#region 顶部信息 银行下拉导入导出
const findBankCombo_data = ref('')
const myBank = reactive({
    myBankName: '',
    myBankNum: "",
    btlFile: '',
})
const findBankCombo_list = ref([])
const findBankCombo_change = (e, x) => {

    if (e) {

        findBankCombo_data.value = e
        for (let i = 0; i < findBankCombo_list.value.length; i++) {

            if (e == findBankCombo_list.value[i].id) {
                myBank.myBankName = findBankCombo_list.value[i].bankName
                myBank.myBankNum = findBankCombo_list.value[i].cardNo
                find_data.myBankName = findBankCombo_list.value[i].bankName
                find_data.myBankNo = findBankCombo_list.value[i].cardNo
            }
        }
    } else {
        findBankCombo_data.value = ''
        myBank.myBankName = ''
        myBank.myBankNum = ''

        find_data.myBankName = ''
        find_data.myBankNo = ''
    }
}
// 导入
const importfeeBtl_btn = () => {
    return ElMessage({
        message: '请先选择一个银行账户',
        type: 'warning',
    })
}

const handleAvatarSuccess = (response, uploadFile) => {
    if (response.code == 1) {
        list_api()

        return ElMessage({
            message: response.msg,
            type: 'success',
        })
    } else {
        return ElMessage({
            message: response.msg,
            type: 'warning',
        })
    }

}

const beforeAvatarUpload = (rawFile) => {
    myBank.btlFile = rawFile
    console.log(rawFile)
    let type = rawFile.name.split('.')[rawFile.name.split('.').length - 1]
    if (type == 'xlsx' || type == 'xls' || type == 'csv') {
        return true
    } else {
        return ElMessage.error('请上传Excel文件!')
    }

}
// 下载模版
const btlModelDown_btn = async () => {
    btlModelDown().then((res) => {
        console.log(res)
        downFiles(res, '单位管理后台系统-银行记账列表')

    })


}

//#endregion

//#region 表格数据处理
const table_data_list = reactive([
    { label: '交易时间', field: 'tradeTime', width: 170, off: true },
    { label: '客户名称', field: 'cusName', width: 170, off: true },
    { label: '银行名称', field: 'myBankName', width: 170, off: true },
    { label: '银行账号', field: 'myBankNum', width: 170, off: true },
    { label: '报销状态', field: 'isCheck', width: 100, off: true },
    { label: '金额类型', field: 'moneyTypeName', width: 120, off: true },
    { label: '收入', field: 'tradeInMoney', width: 100, off: true },
    { label: '支出', field: 'tradeOutMoney', width: 100, off: true },
    { label: '金额', field: 'balance', width: 100, off: true },
    { label: '摘要', field: 'remark', width: 220, off: true },
    { label: '对方户名', field: 'transName', width: 170, off: true },
    { label: '对方账号', field: 'transNum', width: 170, off: true },
    { label: '添加时间', field: 'addTime', width: 170, off: true },
    { label: '操作编号', field: 'operMark', width: 170, off: true },
    { label: '操作备注', field: 'operNote', width: 220, off: true },
    { label: '结算人', field: 'settleUser', width: 120, off: true },

])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '银行流水',
        tbNum: "bank_statement",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion


const defaultTime = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
//#region 分页列表
const list_data = ref([])
const timeType_list = reactive([
    {
        value: 0,
        label: '添加时间',
    },
    {
        value: 1,
        label: '交易时间',
    },
])
const isCheck_list = reactive([
    {
        value: 'NO_CHECK',
        label: '未操作',
    },
    {
        value: 'CANCELLATION',
        label: '已报销',
    }, {
        value: 'SETTLED',
        label: '已结算',
    },
])
const tradeStatus_list = reactive([{
    value: 0,
    label: '收入',
},
{
    value: 1,
    label: '支出',
},])
const timeTypeTime = ref('')
const timeTypeTime_btn = (e) => {
    if (e) {
        timeTypeTime.value = e
        find_data.stime = timeTypeTime.value[0]
        find_data.etime = timeTypeTime.value[1]
    } else {
        timeTypeTime.value = ''
        find_data.stime = ''
        find_data.etime = ''
    }
}
const findMtypeCombo_list = ref([])
const upManageOptions = ref([])
const moneyTypeIds_list = ref('')
// const moneyTypeIds_chang = (e) => {
//     if (e) {
//         find_data.moneyTypeIds = [e]
//     } else {
//         find_data.moneyTypeIds = []
//     }
// }
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    cusName: '',
    timeType: 0,
    stime: '',
    etime: '',
    isCheck: '',
    isLink: '',
    moneyTypeIds: [],
    myBankName: '',
    myBankNo: '',
    operMark: '',
    operNote: '',
    remark: '',
    tradeMoney: '',
    tradeStatus: '',
    transName: '',
    settleUname: "",
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}
const totalGath = ref(0)
const totalPay = ref(0)
const getBalance = ref(0)
const list_api = () => {

    findBankTradeList(find_data).then(res => {
        list_data.value = res.data.list.list
        total.value = res.data.list.total
        totalGath.value = res.data.totalGath
        totalPay.value = res.data.totalPay
        getBalance.value = res.data.bankBalance
    })
}
//#endregion

//#region 添加
const myBankName_change = (e) => {
    let data = []
    for (let i = 0; i < findBankCombo_list.value.length; i++) {
        if (e == findBankCombo_list.value[i].bankName) {
            data.push(findBankCombo_list.value[i])
        }
    }
    if (data.length > 2) {
        return ElMessage({
            message: '银行名有重复请联系管理员',
            type: 'warning',
        })
    } else {
        add_data.myBankNum = data[0].cardNo
    }
    findBalanceByBankInfo({
        myBankName: data[0].bankName,
        myBankNum: data[0].cardNo,
    }).then(res => {
        add_data.balance = res.data
        balance_data.value = res.data
    })


}
const add_off = ref(false)
const title = ref('添加银行流水')
const add_data = reactive({
    balance: '0',
    cusName: "",
    moneyTypeId: "",
    myBankName: "",
    myBankNum: "",
    remark: "",
    tradeMoney: "",
    tradeStatus: "",
    tradeTime: "",
    transName: "",
    transNum: "",
    id: "",
})
const add_btn = () => {
    title.value = '添加银行流水'
    form_off.value = false
    add_data.balance = ''
    add_data.cusName = ''
    add_data.moneyTypeId = ''
    add_data.myBankName = ''
    add_data.myBankNum = ''
    add_data.remark = ''
    add_data.tradeMoney = ''
    add_data.tradeStatus = ''
    add_data.tradeTime = ''
    add_data.transName = ''
    add_data.transNum = ''
    add_data.id = ''
    // add_data.cusIds = []
    // add_data.cusOptions = []
    // add_data.cusObjArr = []
    findComboCusList({
        find: '',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.code == 1) {
            cusOptions.value = res.data;
            cusOptions2.value = res.data;

            // 追加已选中的数据
            // if (cusObjArr.value.length > 0) cusOptions.value = cusObjArr.value.concat(cusOptions.value);
        }
    })
    zhichu.value = true
    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const headerdragend = (newWidth, oldWidth, column) => {
    console.log(newWidth, oldWidth, column)
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (column.property == table_data_list_new.value[i].field) {
            table_data_list_new.value[i].width = newWidth
        }
    }
}
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const form_off = ref(false)
const up_btn = () => {
    form_off.value = true
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改银行流水'


    add_data.balance = table_list.value[0].balance

    // cusIds.value = []
    // cusOptions.value = []
    // cusObjArr.value = []
    // 设置客户数据
    if (table_list.value[0].cusName) {
        let phoneArr = [];
        table_list.value[0].cusName.split('/@').forEach(it => { phoneArr.push(it.split(',')[1]) });
        findComboCusList({
            find: phoneArr.join(','),
            page: {
                pageNum: 1,
                pageSize: 20,
            },
        }).then((res) => {
            if (res.code == 1) {
                cusOptions.value = res.data;
                cusOptions2.value = res.data;
                // let cusIds = [];
                // cusOptions.value.forEach(it => { cusIds.push(it.id); });

                // 赋值
                // cusIds.value = cusIds;
                // cusObjArr.value = cusOptions.value;
            }
        });
    }
    add_data.cusName = table_list.value[0].cusName
    add_data.moneyTypeId = table_list.value[0].moneyTypeId
    add_data.myBankName = table_list.value[0].myBankName
    add_data.myBankNum = table_list.value[0].myBankNum
    add_data.remark = table_list.value[0].remark

    if (table_list.value[0].tradeInMoney > 0) {
        add_data.tradeMoney = table_list.value[0].tradeInMoney
        add_data.tradeStatus = 0
        zhichu.value = true
    } else if (table_list.value[0].tradeOutMoney > 0) {
        add_data.tradeMoney = table_list.value[0].tradeOutMoney
        add_data.tradeStatus = 1
        zhichu.value = false
    }


    add_data.tradeTime = table_list.value[0].tradeTime
    add_data.transName = table_list.value[0].transName
    add_data.transNum = table_list.value[0].transNum
    add_data.id = table_list.value[0].id


    add_off.value = true
}
//#endregion

// 提交
const zhichu = ref(true)
const change_tradeStatus = (e) => {
    add_data.tradeMoney = ''
    if (e == 0) {
        zhichu.value = true
    } else {
        zhichu.value = false
    }
}
let balance_data = ref(0)
const change_tradeMoney = (e) => {

    if (!add_data.myBankName) {
        add_data.tradeMoney = ''
        return ElMessage({
            message: '请先选择我的银行',
            type: 'warning',
        })
    }
    console.log(add_data.tradeStatus)
    if (add_data.tradeStatus == 0 || add_data.tradeStatus == 1) {

    } else {
        add_data.tradeMoney = ''
        return ElMessage({
            message: '请先选择收支状态',
            type: 'warning',
        })
    }

    if (add_data.tradeStatus == '0') {
        let num = Number(balance_data.value) + Number(e)
        add_data.balance = Math.round(num * 100) / 100
    } else {
        let num = Number(balance_data.value) - Number(e)
        add_data.balance = Math.round(num * 100) / 100
    }

    // console.log(add_data.balance)
}
const ok_btn = () => {
    if (!add_data.myBankName) {
        return ElMessage({
            message: '请输入银行名称',
            type: 'warning',
        })
    } else if (!add_data.myBankNum) {
        return ElMessage({
            message: '请输入银行卡号',
            type: 'warning',
        })
    } else if (!add_data.tradeMoney) {
        return ElMessage({
            message: '请输入交易金额',
            type: 'warning',
        })
    }
    // if (cusObjArr.value) {
    //     let arr = [];
    //     cusObjArr.value.forEach(it => {
    //         arr.push(it.cusRealName + ',' + it.cusPhone);
    //     });
    //     add_data.cusName = arr.join('/@');
    // }
    // return console.log(add_data)
    if (title.value == '添加银行流水') {

        addBtl(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {

        modifyBtl(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}
//#region 转账
const transfer_off = ref(false)
const transfer_data = reactive({
    myBankName: '',
    myBankNum: '',
    remark: '',
    tradeMoney: '',
    tradeTime: '',
    transName: '',
    transNum: '',
})
const transfer_btn = () => {
    transfer_data.myBankName = ''
    transfer_data.myBankNum = ''
    transfer_data.remark = ''
    transfer_data.tradeMoney = ''
    transfer_data.tradeTime = ''
    transfer_data.transName = ''
    transfer_data.transNum = ''
    transfer_off.value = true
}
const transfer_myBankName_change = (e) => {
    let data = []
    for (let i = 0; i < findBankCombo_list.value.length; i++) {
        if (e == findBankCombo_list.value[i].bankName) {
            data.push(findBankCombo_list.value[i])
        }
    }
    if (data.length > 2) {
        return ElMessage({
            message: '银行名有重复请联系管理员',
            type: 'warning',
        })
    } else {
        transfer_data.myBankNum = data[0].cardNo
    }


}
const transfer_myBankName_change2 = (e) => {
    let data = []
    for (let i = 0; i < findBankCombo_list.value.length; i++) {
        if (e == findBankCombo_list.value[i].bankName) {
            data.push(findBankCombo_list.value[i])
        }
    }
    if (data.length > 2) {
        return ElMessage({
            message: '银行名有重复请联系管理员',
            type: 'warning',
        })
    } else {
        transfer_data.transNum = data[0].cardNo
    }


}
const transfer_ok_btn = () => {
    if (!transfer_data.myBankName) {
        return ElMessage({
            message: '请输入转出银行名称',
            type: 'warning',
        })
    }
    if (!transfer_data.myBankNum) {
        return ElMessage({
            message: '请输入',
            type: 'warning',
        })
    }
    if (!transfer_data.myBankName) {
        return ElMessage({
            message: '请输入转出银行卡号',
            type: 'warning',
        })
    }
    if (!transfer_data.tradeMoney) {
        return ElMessage({
            message: '请输入转账金额',
            type: 'warning',
        })
    }
    if (!transfer_data.tradeTime) {
        return ElMessage({
            message: '请输入转账时间',
            type: 'warning',
        })
    }
    if (!transfer_data.transName) {
        return ElMessage({
            message: '请输入转入银行名称',
            type: 'warning',
        })
    }
    if (!transfer_data.transNum) {
        return ElMessage({
            message: '请输入转入银行卡号',
            type: 'warning',
        })
    }
    ElMessageBox.confirm(
        `是否确认转账?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            transfer(transfer_data).then(res => {
                if (res.code == 1) {
                    transfer_off.value = false
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {


        })

}

//#endregion

//#region 互转
const confirmTransEach_off = ref(false)
const confirmTransEach_on = ref(1)
const confirmTransEach_btn = () => {
    if (table_list.value.length != 2) {
        return ElMessage({
            message: '请选择两条数据！',
            type: 'warning',
        })
    }
    if (table_list.value[0].tradeInMoney > 0) {
        if (table_list.value[1].tradeOutMoney <= 0) {
            return ElMessage({
                message: '数据必须为一收一支',
                type: 'warning',
            })
        }
    } else if (table_list.value[0].tradeOutMoney < 0) {
        if (table_list.value[1].tradeInMoney <= 0) {
            return ElMessage({
                message: '数据必须为一收一支',
                type: 'warning',
            })
        }
    }
    ElMessageBox.confirm(
        `是否确认互转?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            confirmTransEach({
                transInId: table_list.value[0].tradeInMoney > 0 ? table_list.value[0].id : table_list.value[1].id,
                transOutId: table_list.value[0].tradeOutMoney > 0 ? table_list.value[0].id : table_list.value[1].id,
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })
    // confirmTransEach_on.value = 1
    // confirmTransEach_off.value = true
}
const qiehuan = () => {
    if (confirmTransEach_on.value == 1) {
        confirmTransEach_on.value = 2
    } else {
        confirmTransEach_on.value = 1
    }

}
const confirmTransEach_ok_btn = () => {


}

//#endregion

//#region 银行账充值下账
const downBtlRecharge_off = ref(false)
const downBtlRecharge_data = reactive({
    id: '',
    userId: '',
})
const downBtlRecharge_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    downBtlRecharge_data.id = table_list.value[0].id
    if (table_list.value[0].cusName) {
        let data = table_list.value[0].cusName.split(',')[1]
        downBtlRecharge_data.userId = data
    } else {
        downBtlRecharge_data.userId = ''
    }
    downBtlRecharge_off.value = true
}

const downBtlRecharge_ok_btn = () => {
    ElMessageBox.confirm(
        `是否确认银行账充值下账?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            downBtlRecharge(downBtlRecharge_data).then(res => {
                if (res.code == 1) {
                    list_api()
                    downBtlRecharge_off.value = false
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
          

        })

}

//#endregion


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        `是否确认删除?`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delBtl({
                ids: [table_list.value[0].id],
                myBankNum: table_list.value[0].myBankNum
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('bank_statement', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion
//#region 导出
const ex_getWalletListForBack_btn = () => {
    expBtlBankEx(find_data).then(res => {
        if (res.code == 1) {
            const data = [
                ['交易时间', '客户名称', '银行名称', '银行账号', '报销状态', '金额类型', '收入', '支出', '金额', '摘要', '对方户名', '对方账号', '添加时间', '操作编号', '操作备注', '结算人',],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {
                    tradeTime: res.data[i].tradeTime,
                    cusName: res.data[i].cusName,
                    myBankName: res.data[i].myBankName,
                    myBankNum: res.data[i].myBankNum,
                    isCheck: res.data[i].isCheck == 'NO_CHECK' ? '未操作' : res.data[i].isCheck == 'CANCELLATION' ? '已报销' : res.data[i].isCheck == 'SETTLED' ? '已结算' : '无',
                    moneyTypeName: res.data[i].moneyTypeName,
                    tradeInMoney: res.data[i].tradeInMoney,
                    tradeOutMoney: res.data[i].tradeOutMoney,
                    balance: res.data[i].balance,
                    remark: res.data[i].remark,
                    transName: res.data[i].transName,
                    transNum: res.data[i].transNum,
                    addTime: res.data[i].addTime,
                    operMark: res.data[i].operMark,
                    operNote: res.data[i].operNote,
                    settleUser: res.data[i].settleUser,

                }
                data.push(Object.values(ps))
            }

            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '单位管理后台系统-银行流水列表.xlsx');
            findCusWalletPages_list()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

</script>

<style scoped lang='scss'>
.route-tips {
    max-width: 500px !important;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
